import 'package:cross_ecommerce_app/entity/product.dart';
import 'package:flutter/material.dart';

class ProductUpdatePage extends StatefulWidget {
  final Product product;

  ProductUpdatePage({required this.product});

  @override
  _ProductUpdatePageState createState() => _ProductUpdatePageState();
}

class _ProductUpdatePageState extends State<ProductUpdatePage> {
  final _formKey = GlobalKey<FormState>();
  String? _title;
  double? _price;
  String? _description;
  String? _imageUrl;
  String? _brand;
  String? _category;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('修改商品'),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            TextFormField(
              initialValue: widget.product.title,
              onSaved: (value) {
                _title = value ?? '';
              },
            ),
            TextFormField(
              initialValue: widget.product.price.toString(),
              keyboardType: TextInputType.number,
              onSaved: (value) {
                _price = double.tryParse(value ?? '0');
              },
            ),
            TextFormField(
              initialValue: widget.product.description,
              onSaved: (value) {
                _description = value ?? '';
              },
            ),
            TextFormField(
              initialValue: widget.product.imageUrl,
              onSaved: (value) {
                _imageUrl = value ?? '';
              },
            ),
            TextFormField(
              initialValue: widget.product.brand,
              onSaved: (value) {
                _brand = value ?? '';
              },
            ),
            TextFormField(
              initialValue: widget.product.category,
              onSaved: (value) {
                _category = value ?? '';
              },
            ),
            ElevatedButton(
              onPressed: () {
                if (_formKey.currentState != null) {
                  _formKey.currentState!.save();
                  if (_title != null && _price != null && _description != null && _imageUrl != null && _brand != null && _category != null) {
                    widget.product.title = _title!;
                    widget.product.price = _price!;
                    widget.product.description = _description!;
                    widget.product.imageUrl = _imageUrl!;
                    widget.product.brand = _brand!;
                    widget.product.category = _category!;
                    Navigator.pop(context);
                  }
                }
              },
              child: Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}